angular.module('starter.services', [])


  .factory('$$LocalStorage', function() {
    return {
      setVar: function(key, data) {
        return window.localStorage.setItem(key, data);
      },
      getVar: function(key) {
        return window.localStorage.getItem(key);
      },
      /**
       * [把传入的对象转为字符串 进行存储]
       * @param {[Object]} data [js对象]
       */
      setObj: function(key, data) { //
        window.localStorage.setItem(key, window.JSON.stringify(data));
      },
      /**
       * 把json字符串转js对象
       * @return {[object]}     [对象]
       */
      getObj: function(key) {
        return window.JSON.parse(window.localStorage.getItem(key));
      },
      remove: function(key) {
        window.localStorage.removeItem(key);
      },
      removeAll: function() {
        window.localStorage.clear();
      }
    };
  })

  // 图片选择
  .factory('$$cordovaImagePicker', ['$rootScope', '$cordovaImagePicker', function($rootScope, $cordovaImagePicker) {
    // 如果是app才使用图片选择
    if (ionic.Platform.isWebView() == false) {
      return {};
    }
    return $cordovaImagePicker;
  }])

  // 摄像头
  .factory('$$cordovaCamera', ['$rootScope', '$cordovaCamera', function($rootScope, $cordovaCamera) {
    // 如果是app才使用摄像头
    if (ionic.Platform.isWebView() == false) {
      return {};
    }
    return $cordovaCamera;
  }])


  // 获取定位
  .factory('$$cordovaGeolocation', ['$rootScope', '$cordovaGeolocation', function($rootScope, $cordovaGeolocation) {
    // 如果是app才使用获取定位
    if (ionic.Platform.isWebView() == false) {
      return {};
    }
    return $cordovaGeolocation;
  }])

  // app版本更新
  // $cordovaFileOpener2, $cordovaFileTransfer, $cordovaAppVersion
  .factory('$$AppUpdateService', function($rootScope, $ionicPopup, $ionicPlatform, $$LocalStorage, $$CommonService, $timeout, $ionicLoading, $cordovaFileOpener2, $cordovaFileTransfer, $http, $cordovaAppVersion) {
    // 此service 只是app使用
    if (ionic.Platform.isWebView() == false) {
      return {};
    }
    // alert("AppUpdateService");
    // 开始下载app
    function downloadApp(downloadUrl, isForce) {
      // if 苹果系统
      if ($rootScope.config.isIOS) {
        $ionicPopup.show({
          title: "APP版本",
          subTitle: "请到苹果商店更新",
          // scope: scope,
          buttons: [{
            text: '确定',
            type: 'button button-calm',
            onTap: function() {
              ionic.Platform.exitApp();
            }
          }]
        });
        return;
      }
      $ionicLoading.show({
        template: "已经下载：0%"
      });
      var targetPath = "/sdcard/Download/bannitongyou.apk";
      var trustHosts = true;
      var options = {};
      $cordovaFileTransfer.download(downloadUrl, targetPath, options, trustHosts).then(
        function(result) {
          // alert(JSON.stringify(result));
          if (isForce) {
            // 下载好 退出程序
            ionic.Platform.exitApp();
          }
          // 打开下载好的app
          $cordovaFileOpener2.open(targetPath, 'application/vnd.android.package-archive').then(function() {
            // 成功
          }, function(err) {
            console.log(err);
          });
          $ionicLoading.hide();
        },
        function(err) {
          $ionicLoading.show({
            template: "下载失败",
            duration: 1000
          });
          if (isForce) {
            // 下载失败 退出程序
            ionic.Platform.exitApp();
          }
        },
        function(progress) {
          $rootScope.loaded = progress.loaded;
          $rootScope.total = progress.total;
          $timeout(function() {
            var downloadProgress = (progress.loaded / progress.total) * 100;
            $ionicLoading.show({
              template: "已经下载：" + Math.floor(downloadProgress) + "%"
            });
            if (downloadProgress > 99) {
              $ionicLoading.hide();
            }
          }, 100);
        });
    }

    return {
      // 检查版本更新
      downloadapk: function(appurl,isForce) {
        downloadApp(appurl,false);
      },
      // 检查版本更新
      checkVersion: function() {
        // alert("checkVersion");
        // 获取App 内的版本信息
        document.addEventListener("deviceready", function() {
          $ionicPlatform.ready(function() {
            $cordovaAppVersion.getVersionNumber()
              .then(function(version) {
                $rootScope.config.version = version;
                // APP是否需要更新最新版本
                // 最新版本信息
                $$CommonService.getAppVersion("" + $rootScope.config.version, ($rootScope.config.isIOS ? 2 : 1))
                  .then(function(res) {
                    if($rootScope.config.version==res.data.versionId){
                      return;
                    }
                    // 强制更新
                    if (res.data.isForce == 1) {
                      $rootScope.appstate.suitableVsersion = res.data;
                      $$LocalStorage.setObj("appstate", $rootScope.appstate);
                      $ionicPopup.show({
                        title: "APP版本",
                        subTitle: "需要更新到最新版" + res.data.versionId,
                        // scope: scope,
                        buttons: [{
                          text: '取消',
                          type: 'button button-light',
                          onTap: function() {
                            ionic.Platform.exitApp();
                          }
                        }, {
                          text: '确定',
                          type: 'button button-calm',
                          onTap: function() {
                            downloadApp($rootScope.appstate.suitableVsersion.appUrl, true);
                          }
                        }]
                      });
                    } else {
                      // 发现新版本 提示用户是否更新
                      if ($rootScope.appstate.suitableVsersion.versionId !== res.data.versionId) {
                        // 更新当前最新版本
                        $rootScope.appstate.suitableVsersion = res.data;
                        $$LocalStorage.setObj("appstate", $rootScope.appstate);
                        $ionicPopup.show({
                          title: "更新提示",
                          subTitle: "发现新版本" + $rootScope.appstate.suitableVsersion.versionId + "，是否立即更新",
                          // scope: scope,
                          buttons: [{
                            text: '暂不',
                            type: 'button button-light',
                            onTap: function() {}
                          }, {
                            text: '更新',
                            type: 'button button-calm',
                            onTap: function(e) {
                              downloadApp($rootScope.appstate.suitableVsersion.appUrl, false);
                            }
                          }]
                        });
                      } else {
                        // 没有更新的新版
                        // 已经提示过当前最新的版本是否需要更新
                      }
                    }
                  }, function(res) {
                    // $ionicLoading.show({
                    //   template: "版本检测失败",
                    //   duration: 1000
                    // });
                  }); // ajax getAppVersion(fn)

              }); //$cordovaAppVersion.getVersionNumber()

          }); // ionicPlatform.ready
        }, false); // deviceready
      },

    };
  })

;
